﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ViCode_LeVi.Data;

namespace ViCode_LeVi.Controls.ControlsWin
{
    public partial class UserControl_Image : UserControl
    {
        public UserControl_Image()
        {
            InitializeComponent();
            this.Load += new EventHandler(UserControl_Image_Load);
        }

        void UserControl_Image_Load(object sender, EventArgs e)
        {
            LoadImage();
        }

        public void LoadImage()
        {
            try
            {
                if (IndexImage >= 0 && IndexImage < ProjectData.Intance.ImageInfos.Length)
                {
                    var pic = ProjectData.Intance.ImageInfos[IndexImage];
                    if (pic != null)
                    {
                        try
                        {
                            pictureBox1.Image = byteArrayToImage(pic.Info);
                        }
                        catch { }
                    }
                }
            }
            catch { }
        }
        [Browsable(true)]
        public int IndexImage { get; set; }
        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }
        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            if (byteArrayIn == null || byteArrayIn.Length == 0)
                return null;
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            // open file dialog
            OpenFileDialog open = new OpenFileDialog();
            // image filters
            open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
            if (open.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // display image in picture box
                    pictureBox1.Image = new Bitmap(open.FileName);
                    if (IndexImage >= 0 && IndexImage < ProjectData.Intance.ImageInfos.Length)
                    {
                        var pic = ProjectData.Intance.ImageInfos[IndexImage];
                        if(pic != null)
                            ProjectData.Intance.ImageInfos[IndexImage].Info = imageToByteArray(pictureBox1.Image);
                    }
                }
                catch { }
            }
        }
    }
}
